<?php

namespace app\admin\controller;

use app\models\{Agent as Agents, Region, AgentLog, Subcate, Cate, Product, Withdraw, Promo, Order, Douyin, Pkey, Coupon};
use think\Db;
use think\Validate;
use EasyWeChat\Factory;


class Agent extends Base
{

    public function import_product()
    {
        $imageFilePath = $_SERVER['DOCUMENT_ROOT'] . '/product/'; //图片本地存储的路径
        if (!file_exists($imageFilePath)) { //如果目录不存在则递归创建
            mkdir($imageFilePath, 777, true);
        }
        try {
            //上传excel文件
            $file = request()->file('file');
            $file_size = $_FILES['file']['size'];
            if ($file_size > 10 * 1024 * 1024) {
                $this->error('文件大小不能超过10M');
                exit();
            }
            //将文件保存到public/uploads目录下面
            $info = $file->validate(['ext' => 'xls,xlsx'])->move('./product');
            $text = [];
            if ($info) {
                $extension = $info->getExtension();
                //获取上传到后台的文件名
                $fileName = $info->getSaveName();
                //获取文件路径
                $filePath = $_SERVER['DOCUMENT_ROOT'] . '/product' . DIRECTORY_SEPARATOR . $fileName;
                $results = importExcelWithImages($filePath);
                // 引用PHPExcel类
                if ($extension == 'xlsx') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
                } else if ($extension == 'xls') {
                    $objReader = \PHPExcel_IOFactory::createReader('Excel5');
                } else {
                    return json(['status' => '1', 'mag' => '文件拓展出错']);
                }
                $objReader->setReadDataOnly(true);
                $obj_PHPExcel = $objReader->load($filePath, $encode = 'utf-8');  //加载文件内容,编码utf-8
                $objWorksheet = $obj_PHPExcel->getsheet(0);
                $data = $objWorksheet->toArray();
                if (count($data) <= 1) {
                    return json(['status' => '1', 'mag' => '数据必须超过一条']);
                }
                $title = $data[0];
                unset($data[0]);
                $saves = [];
                $saves2 = [];
                foreach ($data as $k => $row) {
                    if (count($row) != 9 && count($row) != 10) {
                        $text[] = '第' . ($k + 1) . '行跳过,数据表格错误,请下载最新示例';
                        continue;
                    }
                    $param = [];
                    foreach ($row as $ss => $rson) {
                        $rson = trim($rson);
                        if ($ss >= 6 && $ss != 9 && !empty($rson)) {
                            $param[] = ['name' => $title[$ss] ?? '', 'numbers' => $rson];
                        }
                    }
                    try {
                        //查找品牌是否存在
                        $agent = (new Agents())->where('nickname', $row[0])->find();
                        if (empty($agent)) {
                            $text[] = '第' . ($k + 1) . '行跳过,品牌不存在';
                            continue;
                        }
                        $cate = (new Cate())->where(['name' => $row[3]])->find();
                        if (empty($cate)) {
                            $text[] = '第' . ($k + 1) . '行跳过,平台分类不存在';
                            continue;
                        }
                        if (empty($row[2])) {
                            $text[] = '第' . ($k + 1) . '行跳过,产品名称不能为空';
                            continue;
                        }
                        $product = (new Product())->where(['title' => $row[2], 'isdel' => 1])->find();
                        if (!empty($product)) {
                            $saves2[] = [
                                'id' => $product['id'] ?? '',
                                'numbers' => $row[1] ?? '',
                                'inventory' => $row[5] ?? 0,
                                'cate' => $cate['id'] ?? '',
                                'agentid' => $agent['id'] ?? '',
                                'price' => $row[4] ?? 0,
                                'title' => $row[2] ?? '',
                                'descs' => $row[2] ?? '',
                                'parame' => json_encode($param, true),
                                'dealer' => $row['9'],
                            ];
                        } else {
                            $saves[] = [
                                'numbers' => $row[1] ?? '',
                                'inventory' => $row[5] ?? 0,
                                'cate' => $cate['id'] ?? '',
                                'agentid' => $agent['id'] ?? '',
                                'price' => $row[4] ?? 0,
                                'title' => $row[2] ?? '',
                                'descs' => $row[2] ?? '',
                                'parame' => json_encode($param, true),
                                'dealer' => $row['9'],
                            ];
                        }
                    } catch (\Exception $e) {
                        $text[] = '第' . ($k + 1) . '行失败跳过,' . $e->getMessage();
                        continue;
                    }
                }
                //dump($saves);dump($saves2);die;
                if (count($saves) > 0) {
                    Db::startTrans();
                    try {
                        (new Product())->allowfield(true)->saveAll($saves);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $text[] = '导入完成';
                } else {
                    $text[] = '无数据导入';
                }
                if (count($saves2) > 0) {
                    Db::startTrans();
                    try {
                        (new Product())->allowfield(true)->saveAll($saves2);
                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        $this->result([], 1, $e->getMessage());
                    }
                    $text[] = '导入完成';
                } else {
                    $text[] = '无数据导入';
                }
            } else {
                return json(['status' => '1', 'mag' => '文件过大或格式不正确导致上传失败-_-!']);
            }
            return json(['status' => '0', 'data' => $text]);
        } catch (\Exception $e) {
            throw $e;
        }
    }

    public function product()
    {
        if ($this->request->isAjax()) {
            $model = new Product();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['isdel', '=', 1];
            $where[] = ['agentid', '>', 0];
            if (!empty($post['title'])) {
                $where[] = ['title', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['images'])) {
                if ($post['images'] == 2) {
                    $model = $model->where('LENGTH(images) < 5');
                }
            }
            if (!empty($post['agentid'])) {
                $where[] = ['agentid', '=', $post['agentid']];
            }
            if (!empty($post['cate'])) {
                $where[] = ['cate', '=', $post['cate']];
            }
            if (!empty($post['dealer'])) {
                if ($post['dealer'] == '无') {
                    $where[] = ['dealer', '=', null];
                } else {
                    $where[] = ['dealer', '=', $post['dealer']];
                }
            }
            if (!empty($post['isshow'])) {
                $where[] = ['isshow', '=', $post['isshow']];
            }
            if (!empty($post['ishot'])) {
                $where[] = ['ishot', '=', $post['ishot']];
            }
            if (!empty($post['isnew'])) {
                $where[] = ['isnew', '=', $post['isnew']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order(["title" => 'desc', "sort" => "desc"])->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['agent_name'] = '系统';
                if ($lists['agentid'] > 0) {
                    $lists['agent_name'] = (new Agents())->where(['id' => $lists['agentid']])->value('nickname') ?? '';
                }
                $lists['parame'] = json_decode($lists['parame'], true) ?? [];
                $lists['cate_name'] = (new Cate())->where(['id' => $lists['cate']])->value('name') ?? '无';
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            $dealer = (new Product())->group('dealer')->column('dealer');
            return view(null, [
                'dealer' => $dealer,
                'cate' => (new Cate())->field('id,name,isshow')->order(['sort' => 'desc'])->select(),
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select()
            ]);
        }
    }


    public function product_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'title' => 'require',
                'agentid' => 'require',
                'cate' => 'require'
            ], [
                'title.require' => '标题不能为空',
                'agentid.require' => '品牌不能为空',
                'cate.require' => '分类不能为空'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'msg' =>  $validate->getError()]);
            }
            if (empty($data['parame'])) {
                return json(['code' => 1, 'msg' => '请至少填写一个参数值']);
            }
            $data['parame'] = json_encode($data['parame'], true) ?? '';
            if (!empty($data['id'])) {
                if (!empty($have) && $data['id'] != $have['id']) {
                    return json(['code' => 1, 'msg' => '产品已存在，请进行编辑']);
                }
                $res = (new Product())->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($have)) {
                    return json(['code' => 1, 'msg' => '产品已存在，请进行编辑']);
                }
                $res = (new Product())->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'msg' => '操作失败']);
        } else {
            $id = $this->request->get('id/d', 0);
            $row = (new Product())->where('id', $id)->find();
            if (!empty($row)) {
                $row['parame'] = json_decode($row['parame'], true) ?? [];
                $cate = (new Cate())->where('agentid', $row['agentid'])->field('id,name,isshow')->order('sort desc')->select();
            }
            return view('', [
                'row' => $row,
                'agent' => (new Agents())->field('id,nickname,accounts')->where(['status' => [1, 2]])->select(),
                'cate' => $cate ?? []
            ]);
        }
    }

    public function product_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Product();
            $cate = $model->where(['id' => $id])->find();
            if (empty($cate)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'isshow':
                    $status = $cate['isshow'] == 1 ? 2 : 1;
                    break;
                case 'ishot':
                    $status = $cate['ishot'] == 1 ? 2 : 1;
                    break;
                case 'isnew':
                    $status = $cate['isnew'] == 1 ? 2 : 1;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function product_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Product();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['isdel' => 2]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $model = new Agents();
            $post = input();
            $page = input('page/d') ?? 1;
            $limit = input('limit/d') ?? 10;
            $where = array();
            $where[] = ['status', 'in', [1, 2]];
            if (!empty($post['title'])) {
                $where[] = ['accounts|nickname|mobile', 'like', '%' . $post['title'] . '%'];
            }
            if (!empty($post['status'])) {
                $where[] = ['status', '=', $post['status']];
            }
            $count = $model->where($where)->count();
            $page = ($count <= $limit) ? 1 : $page;
            $list = $model->where($where)->order("id desc")->limit($limit)->page($page)->select();
            foreach ($list as $lists) {
                $lists['product'] = (new Product())->where(['agentid' => $lists['id'], 'isdel' => 1])->count();
            }
            return json(['code' => 200, 'msg' => '获取成功', 'data' => $list, 'count' => $count]);
        } else {
            return view(null, []);
        }
    }

    public function agent_edit()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $validate = new Validate([
                'nickname' => 'require|chsAlphaNum|length:2,50',
                'accounts' => 'require|alphaNum|length:2,50'
            ], [
                'nickname.require' => '备注不能为空',
                'nickname.length' => '备注长度控制在2-50个字符',
                'nickname.chsAlphaNum' => '备注只能是汉字、字母和数字',
                'accounts.require' => '账号不能为空',
                'accounts.alphaNum' => '账号只能是字母和数字',
                'accounts.length' => '账号长度控制在2-50个字符'
            ]);
            if (!$validate->check($data)) {
                return json(['code' => 1, 'data' => [], 'msg' => $validate->getError()]);
            }
            if (empty($data['id']) && empty($data['password'])) {
                return json(['code' => 1, 'data' => [], 'msg' => '密码必须填写']);
            }
            if (!empty($data['id']) && empty($data['password'])) {
                unset($data['password']);
            }
            if (!empty($data['password'])) {
                $data['password'] = md5(md5($data['password']));
            }
            $model = new Agents();
            //查找店铺名称、账号是否已经被使用
            $haveshop = $model->where(['accounts' => $data['accounts'], 'status' => [1, 2]])->find();
            if (!empty($data['id'])) {
                if (!empty($haveshop) && $haveshop['id'] != $data['id']) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data, ['id' => $data['id']]);
            } else {
                if (!empty($haveshop)) {
                    return json(['code' => 1, 'data' => [], 'msg' => '账号已被使用']);
                }
                $res = $model->allowfield(true)->save($data);
            }
            if ($res) {
                return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
            }
            return json(['code' => 1, 'data' => [], 'msg' => '操作失败，请重试']);
        } else {
            $model = new Agents();
            $id = $this->request->get('id/d', 0);
            $row = $model->where('id', $id)->find();
            return view('', [
                'row' => $row
            ]);
        }
    }


    public function agent_del()
    {
        $id = input('id');
        if (!empty($id)) {
            $model = new Agents();
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update(['status' => 3]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }


    public function agent_status()
    {
        $id = input('id');
        $field = input('field/s', '');
        if (!empty($id) && !empty($field)) {
            $model = new Agents();
            $agent = $model->where(['id' => $id])->find();
            if (empty($agent)) {
                return json(['code' => 1, 'data' => [], 'msg' => '数据不存在,请刷新页面重试']);
            }
            switch ($field) {
                case 'status':
                    if ($agent['status'] == 3) {
                        return json(['code' => 1, 'data' => [], 'msg' => '账号已被删除']);
                    }
                    $status = $agent['status'] == 1 ? 2 : 1;
                    break;
                case 'openid':
                    $status = null;
                    break;
                default:
                    return json(['code' => 1, 'data' => [], 'msg' => '数据类型错误,请刷新页面重试']);
                    break;
            }
            Db::startTrans();
            try {
                $model->where(['id' => $id])->update([$field => $status]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 1, 'data' => [], 'msg' => $e->getMessage()]);
            }
            return json(['code' => 200, 'data' => [], 'msg' => '操作成功']);
        }
        return json(['code' => 1, 'data' => [], 'msg' => '操作失败']);
    }
}
